<template>
  <div class="register">
    <el-dialog title="注册" :visible.sync="parentData.show" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender">
            <el-option label="女" :value="0" />
            <el-option label="男" :value="1" />
            <el-option label="保密" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作状态" prop="workStatus">
          <el-select v-model="form.workStatus">
            <el-option label="保密" :value="0" />
            <el-option label="工作" :value="1" />
            <el-option label="求职" :value="2" />
            <el-option label="在校" :value="3" />
            <el-option label="摆烂" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            action="avatarUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.avatar" :src="form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="个人简介" prop="userInfo">
          <el-input
            v-model="form.userInfo"
            type="textarea"
            placeholder="请输入个人简介"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="form.code">
            <template slot="append">
              <el-button
                slot="append"
                type="primary"
                :disabled="isDisabled"
                @click="getCode()"
              >{{ buttonName }}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input v-model="form.checkPassword" type="password" autocomplete="off" />
        </el-form-item>
        <div style="text-align: center">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submitForm()">注册</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { sendReg, sendEmail, verifyApi } from '@/api/sys'
import { qiniu } from '@/api/upload'
export default {
  name: 'RegisterIndex',
  props: ['parentData'],
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value.length < 6) {
        callback(new Error('密码不能小于6位字符'))
      } else {
        if (this.form.password !== '') {
          this.$refs['form'].validateField('checkPassword')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      form: {
        nickname: '',
        userInfo: '',
        code: '',
        phone: '',
        email: '',
        avatar: '',
        workStatus: 4,
        gender: 2,
        password: '', // 密码
        checkPassword: '', // 确认密码
        userType: '' // 确认密码
      },
      buttonName: '发送验证码',
      isDisabled: false,
      time: 30,
      rules: {
        // account: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
            message: '请输入正确的手机号码'
          }
        ],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
        userType: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        password: [{ trigger: 'blur', validator: validatePass }],
        checkPassword: [{ trigger: 'blur', validator: validatePass2 }]
      },
      avatarUpload: '',
      imageUrl: '',
      imgArr: ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff']
    }
  },
  methods: {
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const data = {
            code: this.form.code,
            email: this.form.email,
            registerFlag: true
          }
          verifyApi(data).then(res => {
            sendReg(this.form).then(res => {
              this.$message.success(`注册成功，可使用手机号或邮箱进行登录`)
              this.parentData.show = false
            })
            // eslint-disable-next-line handle-callback-err
          }).catch(err => {
            this.$message.error('验证码错误')
            return
          })
        } else {
          return false
        }
      })
    },
    cancel() {
      this.parentData.show = false
    },
    // 获取验证码
    getCode() {
      const me = this
      me.isDisabled = true
      const interval = window.setInterval(() => {
        me.buttonName = `(${me.time}S)后重新发送`
        --me.time
        if (me.time < 0) {
          me.buttonName = '重新发送'
          me.time = 30
          me.isDisabled = false
          window.clearInterval(interval)
        }
      }, 1000)
      const data = {
        sendTo: this.form.email,
        registerFlag: true,
        subject: '充电鸭注册邮件'
      }
      sendEmail(data).then(res => {
        this.$message.success('发送成功,请留意邮箱验证码不是手机验证码')
      })
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      let type = file.type
      type = type.substr(Number(type.lastIndexOf('/')) + 1)
      console.log(file)
      console.log(type)
      const isImageType = this.isImageType(type)
      if (!isImageType) {
        this.$message.error(`只能上传图片格式 ${this.imgArr}`)
      }
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      if (file) {
        // 前端16位MD5无法满足要求，采用服务器上传方式进行
        qiniu(file).then(resp => {
          this.form.avatar = resp.data.fileUrl
        })
      } else {
        this.$message.error('文件上传失败')
        return false
      }
      return isImageType && isLt10M
    },
    isImageType(str) {
      // toLowerCase() 将字符串转换为小写，返回一个新的字符串
      return this.imgArr.indexOf(str.toLowerCase()) !== -1
    }
  }
}
</script>

<style lang="scss" scoped>
  .register{
    clear: both;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
